part of tools;

class VideoWidgetController {
  _VideoWidgetState? state;

  void _bind(_VideoWidgetState state) {
    this.state = state;
  }

  /// 暂停
  void pause() {
    if (state != null) {
      state!.pause();
    }
  }

  /// 播放
  void play() {
    if (state != null) {
      state!.play();
    }
  }

  /// 释放
  void dispose() {
    if (state != null) {
      state!.dispose();
    }
  }

  /// 静音
  void mute() {
    if (state != null) {
      state!.mute();
    }
  }

  /// 不静音
  void notMute() {
    if (state != null) {
      state!.notMute();
    }
  }
}

class VideoWidget extends StatefulWidget {
  /// 视频地址
  final String url;
  final double? width;
  final double? height;
  final double radius;

  /// 重新播放
  final bool rePlay;

  /// 自动播放
  final bool autoPlay;

  final bool showIcon;

  final bool prepared;

  final Function? playingBack;

  final BoxFit? fit;

  final VideoWidgetController? controller;

  ///播放时间
  final Duration? playDuration;
  // 是否可以点击暂停
  final bool canTap;
  ///静音
  final bool mute;
  // 进度
  final bool schedules;
  

  const VideoWidget({
    Key? key,
    required this.url,
    this.width,
    this.height,
    this.radius = 8,
    this.rePlay = false,
    this.autoPlay = true,
    this.showIcon = true,
    this.prepared = false,
    this.playingBack,
    this.fit,
    this.controller,
    this.playDuration,
    this.canTap=true,
    this.mute=false,
    this.schedules=false,
  }) : super(key: key);

  @override
  State<VideoWidget> createState() => _VideoWidgetState();
}

class _VideoWidgetState extends State<VideoWidget> {
  late CachedVideoPlayerPlusController _controller;

  bool _playing = false;
  // 加载中
  bool _prepared = false;
  // 加载失败
  bool _error = false;

  Timer? timer;

  double _sliderValue = 0.0;

  /// 初始化播放器
  void initPlayer() {
    _controller =
        CachedVideoPlayerPlusController.networkUrl(Uri.parse(widget.url))
          ..initialize().then((_) {
            if (mounted) {
              setState(() {
                _prepared = true;
                if (widget.autoPlay) {
                  play();
                }
              });
            }
          });
      ///静音
    _controller.setVolume(widget.mute ? 0 : 1);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    widget.controller?._bind(this);
  }

  @override
  void dispose() {
    _controller.dispose();
    timer?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    _prepared = widget.prepared;
    super.initState();
    initPlayer();
    _controller.addListener(_playerValueChanged);
  }

  void _playerValueChanged() {
    if (_controller.value.isInitialized) {
      if (_controller.value.isPlaying) {
        setState(() {
          _sliderValue=_controller.value.position.inMicroseconds/ _controller.value.duration.inMicroseconds;
          _playing = true;
        });
        if(widget.playDuration != null && timer == null){
              timer = Timer(widget.playDuration!, () {
                //  _controller.pause();
                 _controller.seekTo(Duration(microseconds: 0));
                  timer?.cancel();
                setState(() {
                  timer = null;
                });
              });
        }
         
        if (widget.playingBack != null) {
          widget.playingBack!();
        }
      } else {
        setState(() {
          _playing = false;
        });
      }
    }
    if (_controller.value.hasError) {
      setState(() {
        _prepared = true;
        _error = true;
      });
    }
    if (_controller.value.isCompleted && widget.rePlay) {
      timer = Timer.periodic(Duration(microseconds: 10), (_) {
        timer?.cancel();
        if (!_playing) {
          _controller.dispose();
          // play();
          initPlayer();
          setState(() {
            _playing = true;
          });
          _controller.addListener(_playerValueChanged);
        }
      });
    }
  }

  /// 播放
  void play() async{
    if (_controller.value.isInitialized && mounted) {
      if (widget.playDuration != null) {
             await _controller.seekTo(Duration.zero);
          }
      _controller.play();
    }
  }

  /// 暂停
  void pause() {
    if (_controller.value.isInitialized && mounted) {
      _controller.pause();
    }
  }

  /// 静音
  void mute() {
    if (_controller.value.isInitialized && mounted) {
      _controller.setVolume(0);
    }
  }
  /// 有声音
  void notMute() {
    if (_controller.value.isInitialized && mounted) {
      _controller.setVolume(1);
    }
  }

  @override
  Widget build(BuildContext context) {
    return WidgetVisibilityDetector(
      onAppear: () async{
        if (widget.autoPlay) {
          play();
        }
      },
      onDisappear: () {
        pause();
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(widget.radius),
        child: Stack(
          children: [
             
            widget.fit != null
                ? SizedBox.expand(
                    child: FittedBox(
                      fit: widget.fit!,
                      child: Stack(
                        children: [
                          SizedBox(
                        width: _controller.value.size.width,
                        height: _controller.value.size.height,
                        child: CachedVideoPlayerPlus(_controller),
                      ),
                      stopIcon(),
                     if(widget.schedules) schedule()
                        ],
                      ),
                    ),
                  )
                : Container(
                    width: widget.width,
                    height: widget.height,
                    color: Colors.black,
                    child: Stack(
                      children: [
                        Center(
                        child: AspectRatio(
                          aspectRatio: _controller.value.aspectRatio,
                          child: CachedVideoPlayerPlus(_controller),
                        ),
                      ),
                      stopIcon(isSmall:true),
                      // schedule(isSmall:true)
                    ],
                    ),
                  ),
            
          ],
        ),
      ),
    );
  }

  Widget stopIcon({bool isSmall=false}){
    return Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              top: 0,
              child: InkWell(
                splashColor: Colors.transparent,
                onTap: () {
                  if (widget.showIcon == true) {
                    if (_playing&&widget.canTap) {
                      pause();
                    } else {
                      play();
                    }
                  }
                },
                child: !_prepared
                    ? Container(
                        width: double.infinity,
                        height: double.infinity,
                        decoration: BoxDecoration(color: Colors.black),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              width: 50,
                              height: 50,
                              margin: EdgeInsets.only(bottom: 20),
                              child: CircularProgressIndicator(
                                backgroundColor: Colors.white70,
                                valueColor: AlwaysStoppedAnimation(
                                    Theme.of(context).primaryColor),
                              ),
                            ),
                            Text(
                              "努力加载中...",
                              style: TextStyle(
                                color: Colors.white70,
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      )
                    : Center(
                        child: _error
                            ? Icon(
                                Icons.error,
                                color: Colors.white,
                                size:isSmall?50: 100,
                              )
                            : !_playing && widget.showIcon == true
                                ? Icon(
                                    Icons.play_circle,
                                    color: Colors.white,
                                    size:isSmall?50: 100,
                                  )
                                : Container(),
                      ),
              ),
            );
           
  }

  Widget schedule({bool isSmall=false}){
    return Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Slider(
              value: _sliderValue,
              onChanged: (double value) {
                setState(() {
                  _sliderValue = value;
                });
                //  _controller.seekTo(Duration(milliseconds: 1000));
                // print('-----------------${value.round()}--${_controller.value.duration.inMicroseconds}---${value.round() * _controller.value.duration.inMilliseconds}');
                _controller.seekTo(Duration(microseconds: (value * _controller.value.duration.inMicroseconds).round()));
              },
              activeColor: Color.fromRGBO(35, 103, 239, 1),
              inactiveColor: Colors.grey,
          ),
            
            //  Container(
            //   padding: EdgeInsets.symmetric(horizontal: 15),
            //   child: DiamondNodeSlisder(
            //   ratioValue: _sliderValue,
            //   activeTrackColor: Color(0xFF878E9A),
            //   unActiveTrackColor: Color(0xFFEBEBEB),
            //   height: 10,
            //   maxValue: 0,
            //   minValue: 100,
            //   isRhombus:false,
            //   textShowBool:false,
            //   valueChanged:(value,ratioV) {

            //     setState(() {
            //       _sliderValue = ratioV;
            //     });
            //     _controller.seekTo(Duration(microseconds: (value * _controller.value.duration.inMicroseconds).round()));
            //   },
            // ),
            // ),
            
            
          );
  }
}
